package com.maoslv.configuration;

import com.maoslv.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //post请求之前都需要来校验
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    @Autowired
    MyAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    MyAccessDeniedHandler accessDeniedHandler;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Resource
    DataSource dataSource;

    @Bean
    JwtFilter jwtFilter() throws Exception {
        return new JwtFilter(authenticationManager());
    }

    //密码加密
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    private static final String[] URL_WHITELIST = {
            "/login",
            "/register",
            "/email"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许跨域
        http.cors().and().csrf().disable()
                //配置拦截规则
                .authorizeRequests()
                //白名单直接放行
                .antMatchers(URL_WHITELIST).permitAll()
                //除了白名单外的请求全部都用登录才能访问
                .anyRequest().authenticated()

                //登录配置
                .and()
                .formLogin()

                //登录成功的配置
                .successHandler(loginSuccessHandler)

                //登录失败的配置
                .failureHandler(loginFailureHandler)

                //退出登录
                .and()
                .logout()
                .logoutUrl("user/logout")

                //记住我
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .rememberMeParameter("remember_me")
                .rememberMeCookieName("remember-me")
                .tokenValiditySeconds(7 * 24 * 60 * 60)

                //禁用session
                .and()
                .sessionManagement()

                //不生成session的策略
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                //异常处理器
                .and()
                .exceptionHandling()

                //认证失败处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                //权限异常处理器
                .accessDeniedHandler(accessDeniedHandler)

                //配置自定义的过滤器
                .and()
                .addFilter(jwtFilter())
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }

    /*
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/register");
    }
    */

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        return tokenRepository;
    }
}
